package system.recording

import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Binder
import android.os.Build
import android.os.IBinder

class AudioRecordService : Service() {

    private val notificationId = 999
    private val channelID = "notificationChannelID"
    private val title = "录音服务"
    private val content = "录音服务正在运行..."
    private val description = "AudioRecordService"
    private lateinit var mediaProjectionManager: MediaProjectionManager
    override fun onCreate() {
        super.onCreate()
        mediaProjectionManager =
            getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        initNotification()
    }

    /**
     * 初始化通知栏
     */
    private fun initNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channel = NotificationChannel(channelID, title, NotificationManager.IMPORTANCE_HIGH)
            channel.enableLights(true) //设置提示灯
            channel.lightColor = Color.RED //设置提示灯颜色
            channel.setShowBadge(true) //显示logo
            channel.description = description
            channel.lockscreenVisibility =
                Notification.VISIBILITY_PUBLIC //设置锁屏可见 VISIBILITY_PUBLIC=可见
            manager.createNotificationChannel(channel)
            val builder = Notification.Builder(this, channelID)
            val notification = builder.setAutoCancel(false).setContentTitle(title) //标题
                .setContentText(content) //内容
                .setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher) //设置小图标
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))//设置大图标
                .build()
            startForeground(notificationId, notification)
        } //设置描述
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        val source = intent.getIntExtra("source", 0)
        if (source == 0) {
            initializeDefaultRecording()
        } else if (source == 1) {
            val resultData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra("resultData", Intent::class.java)
            } else {
                intent.getParcelableExtra("resultData")
            }
            resultData?.let {
                initializeSystemRecording(it)
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }


    private var mMediaProjectionCallback: MediaProjectionCallback? = null
    private var mediaProjection: MediaProjection? = null
    private var mRecorder: AudioRecorder? = null


    /**
     * 麦克风
     */
    private fun initializeDefaultRecording() {
        mRecorder = AudioRecorder()
        mRecorder!!.initializeDefaultRecording()
    }

    /**
     * 系统内录音
     */
    private fun initializeSystemRecording(resultData: Intent) {
        mMediaProjectionCallback = MediaProjectionCallback()
        mediaProjection = mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, resultData)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && mediaProjection != null) {
            mRecorder = AudioRecorder()
            mRecorder!!.initializeSystemRecording(mediaProjection)
        } else {
            mediaProjection?.stop()
            stopSelf()
        }
    }

    fun startRecording(): Boolean {
        val result = mRecorder?.startRecording() ?: false
        return mRecorder != null && result
    }

    fun stopRecording(): Boolean {
        val result = mRecorder?.stopRecording()
        return mRecorder != null && result ?: false
    }

    private val binder = AudioRecordServiceBinder()

    inner class AudioRecordServiceBinder : Binder() {
        fun getService(): AudioRecordService {
            return this@AudioRecordService
        }
    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }


    override fun onDestroy() {
        stop()
        super.onDestroy()
    }

    @SuppressLint("WrongConstant")
    private fun stop() {
        mRecorder?.stop()
        mMediaProjectionCallback?.let { mediaProjection?.unregisterCallback(it) }
        mediaProjection?.stop()
        mediaProjection = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(notificationId)
        }
    }


    companion object {
        fun getIntent(context: Context): Intent {
            return Intent(context, AudioRecordService::class.java)
        }
    }

    inner class MediaProjectionCallback : MediaProjection.Callback() {
        override fun onStop() {
            stop()
        }
    }
}
